import { _decorator, Collider2D, Component, Contact2DType, IPhysics2DContact, log, Node, PhysicsSystem2D, v3, Vec2, Vec3 } from 'cc';
import { ModuleBase } from '../ModuleBase';
import { PoolMgr } from '../../FrameWork/Common/NodePoolMgr';
import { Zombie } from '../Object/Zombie';
import { Emitter } from '../../FrameWork/Common/Emitter';
const { ccclass, property } = _decorator;

@ccclass('ZombieMgr')
export class ZombieMgr extends ModuleBase {
    //用于存储产生在场景中的僵尸
    private _arrZombie: Zombie[] = [];
    //第一波僵尸的出生点
    private _arrFirstZombiePos: Vec3[] = [];
    onInit(): void {
        this._arrFirstZombiePos = [
            v3(1350, 222, 0),
            v3(1100, 222, 0),
            v3(1350, 120, 0),
            v3(1250, 110, 0),
            v3(1230, 100, 0),
            v3(1230, 0, 0),
            v3(1230, -100, 0),
            v3(1200, -120, 0),
        ];
        //产生第一波僵尸
        this.createFirstWaveZombie();
        //开启物理系统
        PhysicsSystem2D.instance.enable = true;
        if (PhysicsSystem2D.instance) {
            PhysicsSystem2D.instance.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
        Emitter.instance.on("AllZombieMove", this, this.allZombieMove);
    }


    //碰撞回调
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if (otherCollider.group == 4) {
            console.log("碰到了植物");

        }
    }
    //产生第一波僵尸
    createFirstWaveZombie() {
        for (let i = 0; i < this._arrFirstZombiePos.length; i++) {
            this.addZombie(this._arrFirstZombiePos[i]);
        }
    }
    //产生僵尸
    addZombie(pos: Vec3) {
        let zombieNode = PoolMgr.instance.getNodePool("Zombie").getNode();
        //将僵尸的脚本存储到数组中
        let zombieJs = zombieNode.getComponent(Zombie);
        //将其存入到数组中
        this._arrZombie.push(zombieJs);
        zombieNode.parent = this.node;
        zombieNode.setPosition(pos);
    }

    //销毁僵尸
    destroyZombie(node: Node) {
        PoolMgr.instance.getNodePool("Zombie").destroyNode(node);
        //将其从数组中移除
        let curZombieJs = node.getComponent(Zombie);
        for (let i = 0; this._arrZombie.length; i++) {
            if (this._arrZombie[i] == curZombieJs) {
                this._arrZombie.splice(i, 1);
                break;
            }
        }
    }

    //僵尸移动
    allZombieMove() {
        for (let zombieJS of this._arrZombie) {
            zombieJS.move();
        }
    }

}